<?php

# Admin base controller
class AdminController extends Controller
{
	private $controller_name = DEFAULT_ADMIN_CTRL;
	private $action = 'index';

	protected $main_navigation = '';
	protected $sub_navigation = '';

	function AdminController($public_access = false)
	{
		parent::Controller();

		// helpers
		$this->load->helper('html');
		$this->load->helper('url');
		$this->load->helper('admin');
		$this->load->helper('form');

		$this->load->model('ApplicationConfig');



		// nom du contrôleur courant
		$this->controller_name = $this->uri->segment(2) ? $this->uri->segment(2) : DEFAULT_ADMIN_CTRL;
		// nom de l'action courante
		$this->action = $this->uri->segment(3) ? $this->uri->segment(3) : 'index';

		if (!$public_access && !$this->session->userdata('admin_connect')) {
			// tentative de connexion par cookie
			$email = $this->input->cookie('login');
			$crypted_password = $this->input->cookie('password');

			if (!$this->connect($email, $crypted_password)) {
				redirect('/admin/login/');
			}
		}
	}

	function index()
	{
		redirect('/admin/'.DEFAULT_ADMIN_CTRL);
	}

	/**
	 * Afficher une vue dans le layout admin
	 * @param path: fichier vue du contrôleur courant à afficher
	 * @param data: données à transmettre à la vue
	 */
	function display($path, $data = null)
	{
		$data['context'] = array(
			// nom du contrôleur courant
			'controller_name' => $this->controller_name,
			// nom de l'action courante
			'action' => $this->action,
			// vue courante
			'view' => $path,
			// chemin de la vue
			'view_path' => 'admin/'.$this->controller_name.'/'.$path,
			'main_navigation' => $this->main_navigation,
			'sub_navigation' => $this->sub_navigation ? $this->sub_navigation : $this->action
		);

		$this->load->view('admin/_partials/'.$this->session->userdata('theme').'/admin_layout', $data);
	}

	/**
	 * Connecter un utilisateur
	 * @return true si connexion, sinon false
	 */
	function connect($email, $crypted_password)
	{
		$this->load->model('User', '', TRUE);

		$user = new User();
		$user->email = $email;
		$user->password = $crypted_password;
		$user->last_used_ip = $this->input->ip_address();

		if (($user = $user->connect()) && $user->status_code == 'admin') {
			$sess = array(
				'admin_connect' => true,
				'candidat_connect' => false,
				'user_id' => $user->id,
				'email' => $user->email,
				'name' => $user->name,
				'firstname' => $user->firstname,
				'theme' => 'transdmin'
			);
			$this->session->set_userdata($sess);
			return true;
		}
		$this->session->set_userdata('admin_connect', FALSE);
		return false;
	}

	/**
	 * Déconnecter l'utilisateur de sa session
	 */
	function disconnect()
	{
		$this->load->helper('cookie');

		$this->session->sess_destroy();
		$this->session->set_userdata('admin_connect', FALSE);
		delete_cookie('login');
		delete_cookie('password');
		redirect('/admin/login/');
	}
}
